﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ubatic.Business.Services;
using Ubatic.Common.Dto;
using Ubatic.Ui.Web.Classes;
using Ubatic.Contracts.Services;

namespace Ubatic.Ui.Web.Pages
{
    public partial class UsuariosListado : System.Web.UI.Page
    {
        private const string listPage = "UsuarioListado.aspx";
        private const string detailPage = "UsuarioDetalle.aspx";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                this.LoadGridView();
            }
        }

        private void LoadGridView()
        {
            GridView.DataSource = this.GetUsers();
            GridView.DataBind();
        }

        private List<Usuario> GetUsers()
        {
            ISecurityService svc = ServiceFactory.GetSecurityService();
            return svc.GetUsers();
        }

        private void Delete(long id)
        {
            ISecurityService svc = ServiceFactory.GetSecurityService();
            svc.DeleteUser(id);
            LoadGridView();
        }

        //private void SearchUsers(UserSearchDto searchDto)
        //{
        //    SecurityService svc = new SecurityService();
        //    this.GridView.DataSource = svc.GetUsers(searchDto);
        //    this.GridView.DataBind();
        //}

        protected void btnAddNew_Click(object sender, EventArgs e)
        {
            Response.Redirect(string.Format("{0}?Option={1}", detailPage, (int)OptionCrud.Create));
        }

        protected void GridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView.PageIndex = e.NewPageIndex;
            this.LoadGridView();
        }

        protected void GridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName != "Page")
            {
                string id = e.CommandArgument.ToString();
                OptionCrud optionCrud = OptionCrudHelper.ConvertToEnum(e.CommandName);
                switch (optionCrud)
                {
                    case OptionCrud.Delete:
                        this.Delete(Convert.ToInt64(id));
                        break;
                    default:
                        Response.Redirect(string.Format("{0}?Id={1}&Option={2}", detailPage, id, ((int)optionCrud)));
                        break;
                }
            }
        }

        protected void GridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {

        }
    }
}